/*
 * Copyright (c) 2025 李伟国
 * SQL-API is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.moyu.sql.business.task;

import com.moyu.sql.business.service.IMoyuRequestService;
import com.moyu.sql.business.service.IMoyuSqlExecuteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

/**
 * spring boot 启动之后初始化数据映射相关的任务
 */
@Slf4j
@Component
public class AppStartInitTask implements SmartLifecycle {

    private IMoyuSqlExecuteService moyuSqlExecuteService;

    private IMoyuRequestService moyuRequestService;

    private volatile boolean running = false;

    @Autowired
    public void setIMoyuSqlExecuteService(IMoyuSqlExecuteService moyuSqlExecuteService) {
        this.moyuSqlExecuteService = moyuSqlExecuteService;
    }

    @Autowired
    public void setIMoyuRequestService(IMoyuRequestService moyuRequestService) {
        this.moyuRequestService = moyuRequestService;
    }

    /**
     * 数据开始后初始化数据映射
     */
    @Override
    public void start() {
        running = true;
        log.info("\n\n >>> AppStartInitTask start <<<\n\n");
        // 添加所有映射
        moyuSqlExecuteService.addAllMappedStatement();
        // 构建请求路由
        moyuRequestService.buildRequestRouter();
    }

    /**
     * spring boot 关闭之后清理数据映射相关的任务
     */
    @Override
    public void stop() {
        running = false;
        log.info("\n\n AppStartInitTask stop\n\n");
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    @Override
    public int getPhase() {
        return Integer.MAX_VALUE; // 确保最后执行
    }
}
